//
//  160. 相交链表.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/5/7.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation

/**
 相较链表
 两种解法：
 1. 一种解法：分别求链表的长度，较长的比较短的长多少；然后较长的先走这么多步。直到相等
 2. 二种解法：同时走。走到为nil换成其他的链表。直到相等
 */
class Solution160 {
    func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
        var head1: ListNode? = headA
        var head2: ListNode? = headB
        while head1 !== head2 {
            if head1 != nil {
                head1 = head1?.next
            } else {
                head1 = headB
            }
            if head2 != nil {
                head2 = head2?.next
            } else {
                head2 = headA
            }
        }
        return head1
    }
    static func test() {
        let node1 = createNode()
        let node2 = createNode()
        let solution = Solution160()
        let result = solution.getIntersectionNode(node1, node2)
        print(result)
    }
    
    static func createNode() -> ListNode?{
        let array = [4,1,8,4,5]
        var head: ListNode?
        var p: ListNode?
        for item in array {
            if head == nil {
                head = ListNode(item)
                p = head
            } else {
                let cur = ListNode(item)
                p?.next = cur
                p = cur
            }
        }
        return head
    }
}
